﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessLogicLayer;

namespace PresentationLayer
{
    public partial class frmUsers : Form
    {
        #region Properties
        private frmMain MdiForm { get; set; }
        private enumState State { get; set; }
        enum enumState
        {
            View,
            New,
            Edit
        }
        #endregion

        #region Constructors
        public frmUsers(frmMain pMdiForm)
        {
            InitializeComponent();
            this.MdiForm = pMdiForm;
        }
        #endregion

        #region Events
        private void frmUsers_Load(object sender, EventArgs e)
        {
            this.MdiForm.Event_OnTranslationChanged += new frmMain.OnTranslationChangedHandler(Translate);
            Translate();
            FillComboBoxCurrency();
            FillComboBoxLanguages();
            FillListViewUsers();
            SetButtonsToState(enumState.View);
            SetTextBoxToState(enumState.View);
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            SetButtonsToState(enumState.New);
            SetTextBoxToState(enumState.New);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            SetButtonsToState(enumState.Edit);
            SetTextBoxToState(enumState.Edit);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            SetButtonsToState(enumState.View);
            SetTextBoxToState(enumState.View);
            FillFieldsWithUserDetails();
        }

        private void lsvUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetButtonsToState(enumState.View);
            SetTextBoxToState(enumState.View);
            FillFieldsWithUserDetails();
        }
        #endregion

        #region Public methods
        #endregion

        #region Private methods
        /// <summary>
        /// Gets all languages from the database and fills the languages ComboBox with them.
        /// </summary>
        private void FillComboBoxLanguages()
        {
            if (cboLanguage.Items.Count > 0)
            {
                cboLanguage.Items.Clear();
            }

            ArrayList Languages = this.MdiForm.DataAccess.GetAllLanguages();
            foreach (clsLanguage Language in Languages)
            {
                cboLanguage.Items.Add(Language);
            }
        }

        /// <summary>
        /// Translates every visible element.
        /// </summary>
        private void Translate()
        {
            this.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, "Text", this.Text, 0);
            grpDetails.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, grpDetails.Name, grpDetails.Text, 0);
            lblFirstName.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblFirstName.Name, lblFirstName.Text, 0);
            lblSurname.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblSurname.Name, lblSurname.Text, 0);
            lblPassword.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblPassword.Name, lblPassword.Text, 0);
            lblDateCreated.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblDateCreated.Name, lblDateChanged.Text, 0);
            grpOptions.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, grpOptions.Name, grpOptions.Text, 0);
            btnCancel.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnCancel.Name, btnCancel.Text, 0);
            btnNew.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnNew.Name, btnNew.Text, 0);
            btnEdit.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnEdit.Name, btnEdit.Text, 0);
            btnSave.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, btnSave.Name, btnSave.Text, 0);
            lblLanguage.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblLanguage.Name, lblLanguage.Text, 0);
            lblCurrency.Text = this.MdiForm.DataAccess.GetTranslation(this.Name, lblCurrency.Name, lblCurrency.Text, 0);
            
            InitializeListViewUsers();
        }

        /// <summary>
        /// Initializes the stores ListView.
        /// </summary>
        private void InitializeListViewUsers()
        {
            if (lsvUsers.Columns.Count > 0)
            {
                lsvUsers.Columns.Clear();
            }
            lsvUsers.Columns.Add(this.MdiForm.DataAccess.GetTranslation(this.Name, lsvUsers.Name + "_Column_First name", "First name", 0));
            lsvUsers.Columns.Add(this.MdiForm.DataAccess.GetTranslation(this.Name, lsvUsers.Name + "_Column_Second name", "Second name", 0));
            lsvUsers.View = View.Details;
            lsvUsers.FullRowSelect = true;
            lsvUsers.HideSelection = false;
            lsvUsers.MultiSelect = false;
        }

        /// <summary>
        /// Saves the user.
        /// </summary>
        private void Save()
        {
            if (SaveUser())
            {
                FillListViewUsers();
                SetButtonsToState(enumState.View);
                SetTextBoxToState(enumState.View);
            }
            else
            {
                MessageBox.Show("Error saving user.");
            }
        }

        private Boolean SaveUser()
        {
            Boolean Success = false;
            if (CheckIfTextBoxesEmpty() == false)
            {
                switch (this.State)
                {
                    case enumState.New:
                        if (this.MdiForm.DataAccess.UserExists(txtFirstName.Text, txtSurname.Text) == false)
                        {
                            Success = this.MdiForm.DataAccess.InsertUser(txtFirstName.Text, txtSurname.Text, txtPassword.Text, GetLanguage(), (clsCurrency)cboCurrency.SelectedItem);
                        }
                        else
                        {
                            MessageBox.Show("The user does allready exist.");
                        }
                        break;
                    case enumState.Edit:
                        Success = this.MdiForm.DataAccess.ChangeUser(GetUserID(), txtFirstName.Text, txtSurname.Text, txtPassword.Text, GetLanguage(), (clsCurrency)cboCurrency.SelectedItem);
                        SetLanguage();
                        break;
                }
            }
            return Success;
        }

        /// <summary>
        /// Sets the language changements to the current user if concerned.
        /// </summary>
        private void SetLanguage()
        {
            if (this.MdiForm.DataAccess.Settings.User_Login != null)
            {
                if (this.MdiForm.DataAccess.Settings.User_Login.ID == GetUserID())
                {
                    this.MdiForm.DataAccess.Settings.User_Login.Language = GetLanguage();
                    this.MdiForm.Translate();
                }
            }
        }

        /// <summary>
        /// Returns the actually selected language.
        /// </summary>
        /// <returns>The actually selected language.</returns>
        private clsLanguage GetLanguage()
        {
            clsLanguage Language = (clsLanguage)cboLanguage.SelectedItem;
            return Language;
        }

        /// <summary>
        /// Gets the actually selected user ID.
        /// </summary>
        /// <returns>The ID of the user.</returns>
        private Int32 GetUserID()
        {
            if (lsvUsers.SelectedItems.Count > 0)
            {
                clsUser User = (clsUser)lsvUsers.SelectedItems[0].Tag;
                return User.ID;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// Fills the ListView with users.
        /// </summary>
        private void FillListViewUsers()
        {
            //Delete all ListView items if available.
            if (lsvUsers.Items.Count > 0)
            {
                lsvUsers.Items.Clear();
            }
            //Get all users.
            ArrayList Users = this.MdiForm.DataAccess.GetAllUsers();
            for (Int32 i = 0; i < Users.Count; i++)
            {
                //Get user.
                clsUser User = (clsUser)Users[i];
                //Create item for ListView.
                ListViewItem Item = new ListViewItem(User.FirstName);
                Item.SubItems.Add(User.SecondName);
                Item.Tag = User;
                //Add item to ListView.
                lsvUsers.Items.Add(Item);
            }
            //Resize columns adapted to contents.
            lsvUsers.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            //Select the first item if possible.
            if (lsvUsers.Items.Count > 0)
            {
                lsvUsers.Items[0].Selected = true;
            }
            else
            {
                FillFieldsWithUserDetails();
            }
        }

        /// <summary>
        /// Fills the currency ComboBox with all actual currencies.
        /// </summary>
        private void FillComboBoxCurrency()
        {
            if (cboCurrency.Items.Count > 0)
            {
                cboCurrency.Items.Clear();
            }

            ArrayList Currencies = this.MdiForm.DataAccess.GetAllLatestCurrencies();

            foreach (clsCurrency Currency in Currencies)
            {
                cboCurrency.Items.Add(Currency);
            }

            cboCurrency.SelectedIndex = 0;
        }

        /// <summary>
        /// Get the user information from the ListView and fill the details into the fields.
        /// </summary>
        private void FillFieldsWithUserDetails()
        {
            if (lsvUsers.SelectedItems.Count > 0)
            {
                clsUser User = (clsUser)lsvUsers.SelectedItems[0].Tag;
                lblDateCreatedVal.Text = User.DateCreated.ToString();
                lblDateChangedVal.Text = User.DateChanged.ToString();
                txtFirstName.Text = User.FirstName;
                txtSurname.Text = User.SecondName;
                txtPassword.Text = User.Password;
                clsLanguage UserLanguage = User.Language;
                for (Int32 i = 0; i < cboLanguage.Items.Count; i++)
                {
                    clsLanguage ComboLanguage = (clsLanguage)cboLanguage.Items[i];
                    if (ComboLanguage.ID == UserLanguage.ID)
                    {
                        cboLanguage.SelectedIndex = i;
                    }
                }
                clsCurrency UserCurrency = User.Currency;
                for (Int32 i = 0; i < cboCurrency.Items.Count; i++)
                {
                    clsCurrency ComboCurrency = (clsCurrency)cboCurrency.Items[i];
                    if (ComboCurrency.CurrencyName == UserCurrency.CurrencyName)
                    {
                        cboCurrency.SelectedIndex = i;
                    }
                }
            }
            else
            {
                lblDateCreatedVal.Text = "";
                lblDateChangedVal.Text = "";
                txtFirstName.Text = "";
                txtSurname.Text = "";
                txtPassword.Text = "";
                cboLanguage.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// Applies the state to the buttons.
        /// </summary>
        /// <param name="pState">The state.</param>
        private void SetButtonsToState(enumState pState)
        {
            this.State = pState;
            switch (this.State)
            {
                case enumState.View:
                    btnCancel.Enabled = false;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;
                    if (lsvUsers.SelectedItems.Count > 0)
                    {
                        btnEdit.Enabled = true;
                    }
                    else
                    {
                        btnEdit.Enabled = false;
                    }
                    break;
                case enumState.New:
                    btnCancel.Enabled = true;
                    btnNew.Enabled = false;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    break;
                case enumState.Edit:
                    btnCancel.Enabled = true;
                    btnNew.Enabled = false;
                    btnEdit.Enabled = false;
                    btnSave.Enabled = true;
                    break;
            }
        }

        /// <summary>
        /// Applies the state to the TextBoxes.
        /// </summary>
        /// <param name="pState"></param>
        private void SetTextBoxToState(enumState pState)
        {
            this.State = pState;
            switch (this.State)
            {
                case enumState.View:
                    txtFirstName.Enabled = false;
                    txtSurname.Enabled = false;
                    txtPassword.Enabled = false;
                    lsvUsers.Enabled = true;
                    cboLanguage.Enabled = false;
                    cboCurrency.Enabled = false;
                    break;
                case enumState.New:
                    txtFirstName.Enabled = true;
                    txtSurname.Enabled = true;
                    txtPassword.Enabled = true;
                    lsvUsers.Enabled = false;
                    txtFirstName.Text = "";
                    txtSurname.Text = "";
                    txtPassword.Text = "";
                    lblDateCreatedVal.Text = "";
                    lblDateChangedVal.Text = "";
                    cboLanguage.Enabled = true;
                    cboCurrency.Enabled = true;
                    break;
                case enumState.Edit:
                    txtFirstName.Enabled = true;
                    txtSurname.Enabled = true;
                    txtPassword.Enabled = true;
                    lsvUsers.Enabled = false;
                    cboLanguage.Enabled = true;
                    cboCurrency.Enabled = false;
                    break;
            }
        }

        /// <summary>
        /// Checks the emptyness of the TextBoxes.
        /// </summary>
        /// <returns>True if TextBoxes are empty.</returns>
        private Boolean CheckIfTextBoxesEmpty()
        {
            if (txtFirstName.Text == "")
            {
                return true;
            }

            if (txtSurname.Text == "")
            {
                return true;
            }

            if (txtPassword.Text == "")
            {
                return true;
            }

            if (cboLanguage.SelectedIndex == -1)
            {
                return true;
            }

            return false;
        }
        #endregion
    }
}
